var page=(function(ns){
	
	var pwdForm,tree;
 	
 	ns.actionTemplet = function(e){
 		var funcCode = e.data.func_code;
 		var values = (e.value || '').split('|');
 		return $.map(values, function(h) {
 			var vals  = (h || '').split('-');
 			if(vals[0]){
 				return '<label><input type="checkbox" name="'+funcCode+'"  value="'+vals[0]+'" >'+vals[1]+'</label>';
 			}
 		}).join('');
 	}
 	
    //页面初始化
    ns.init=function(){
        ns.initTree();
        //授权列表
        grid.loadSuccess(function(res){
        	ns.initAuthorizeCheck(res.data);
        });
    }
    
    //初始化树
    ns.initTree=function(){
    	
    	tree = layui.tree.render({
            elem: '#tree' ,
            textField:"org_name",
            idField:"org_id",
            parentField:'parent_org_id',
            data:'/admin/soft/system_user/getOrgData',
            isList:true,                         //是否列表结构数据，如果是，idField，parentField 必填
            expandNode:2,                //可选，默认展开的节点，字符串
            showCheckbox: false,  		//是否显示复选框
            accordion: false, 				//是否开启手风琴模式
            showIcon:function(e){       //显示图标，可为true
            	return e.parent_org_id == 0 ? "&#xe641;" : '&#xe66b;';
            },
//          treeMenu:[                           //可选，存在时则显示更多按钮
//              {title:"新增",onClick:"page.addNode()",enable:function(e){
//              	return e.org_id != 2;
//              }},
//              {title:"编辑",onClick:"page.editNode()",enable:function(e){
//              	return e.org_id != 2;
//              }},
//              {title:"删除",onClick:"page.removeNode()",enable:function(e){
//              	return e.parent_org_id != 0 && e.org_id != 2;
//              }}
//          ],
            loadSuccess:function(data){  //加载成功
                data[0] && tree.selectNode("org_id",data[0].org_id);
            },
            selectedNode: function(obj){ // 选中节点
            	ns.query();
            },
        });
        
    }
    
   //查询
    ns.query=function(){
    	if(ns.gridId!="grid-authorize"){
	    	var filter =  searchs.getData();
	    	var ids = $.map( tree.getAllChildNodes(), function(h) {
	    		return h.org_id;
	    	}).join(',');
	    	if(ids){
				filter.push({opera: "in", field: "org_id", value: ids });
			}
    		grid.load(filter);
    	}else{
    		var  node = tree.getSelectedNode();
    		grid.load([{field: "{org_id}", value: node.org_id || -1}]);
    	}
    }
    
    //新增节点
    ns.addNode=function(){
        var  node = tree.getThisNode(); 
        layer.prompt({
            title:'请输入组织名称',
            formType: 3,
            offset: '25%'
        }, function(text, index){
            var param={ parent_org_id: node.org_id, org_name:text }
            $.ajaxs("/admin/soft/system_user/addOrgData",param,function(res){
                param.org_id= res.data;
                tree.addNode(param,node);
                $.toast(1,"成功新增！");
            });
            layer.close(index);
        });
    }
    
    //编辑节点
    ns.editNode=function(){
        var  node = tree.getThisNode(); 
        layer.prompt({
            title:'重命名',
            formType: 3,
            offset: '25%',
            value:node.org_name
        }, function(text, index){
            var param={org_id:node.org_id,org_name:text,parent_org_id:node.parent_org_id}
            $.ajaxs("/admin/soft/system_user/addOrgData",param,function(res){
                tree.setNodeText(node,text);
                $.toast(1,"成功更新！");
            });
            layer.close(index);
        });
    }
    
    //删除节点
    ns.removeNode=function(){
        var  node = tree.getThisNode();
        var ids = $.map( tree.getAllChildNodes(node), function(h) { return h.org_id;}).join(',');
        $.confirm('确定删除【'+node.org_name+'】?',function(index){
            $.ajaxs("/admin/soft/system_user/deleteOrgData",{orgIds:ids},function(res){
                tree.removeNode(node);
                $.toast(1,"成功删除！");
            });
            layer.close(index);
        });
    }
    
    //新增
    ns.add=function(){
    	var  node = tree.getSelectedNode(); 
    	if(!node){
    		$.toast(0,"请选择部门！");
    		return;
    	}
    	var filter={
            url:"system/userMng/edit",
            oid:"",
            mode:1,
            org_id:node.org_id,
            org_name:node.org_name
        }
        $.openIframe(filter, "新增用户",['600px', '510px']);
    }
    
    //编辑
    ns.edit=function(){
        var selectedRow = grid.getSelectedRows()[0];
        var filter={
            url:"system/userMng/edit",
            oid:selectedRow.user_id,
            mode:2
        }
        $.openIframe(filter, "编辑用户",['600px', '510px']); 
    }
    
    // 删除选中行
    ns.del=function(){
        grid.deleteSelectRow(); 
    }
    
    //启用与禁用
    //mode=0 等于禁用
    ns.enableAndStand=function(mode){
        var selectedRow=grid.getSelectedRows();
        if(!selectedRow[0]){
            $.toast(0,"请先选择数据！");
            return;
        }
        var param={
            data:$.map(selectedRow, function(h) {
                return {
                    user_id: h.user_id,
                    is_enable: mode,
                    land_status:0
                }
            })
        }
        $.confirm( (mode == "1" ? "确认启用？" : "确认禁用？"),function(index){
            $.ajaxs("/admin/soft/system_user/setEnable",param,function(res){
                grid.load();
                $.toast(1, res.msg);
            });
            layer.close(index);
        });
    }
    
    //更新密码
    ns.updatePwd=function(){
    	var selectedRow=grid.getSelectedRows()[0];
    	if(!selectedRow){
    		$.toast(0,"请先选择用户！");
    		return;
    	}
       function successFn(){
    		pwdForm = layui.forms.render("updatePwdForm","/system/userMng/config.xml",{
    		    mode:2,
    		    oid:selectedRow.user_id
    		});
    	}
    	function yesFn(index){
    		var data = pwdForm.getData();
    		if(data.user_pwd!=data.user_pwd_new){
                $.toast(0,"输入的新密码不一致！");
                return;
            }
            $.ajaxs("/admin/soft/system_user/updateUserPwd",{
            	password:selectedRow.user_pwd,
            	newPwd:data.user_pwd,
            	user_id:selectedRow.user_id
            },function  (res) {
                grid.load();
            	layer.close(index);
            });
//  		pwdForm.save(1).then(function(res){
//          	grid.load();
//          	layer.close(index);
//          });
    	}
    	var html="<div id='updatePwdForm'></div>";
    	$.openModalDialog(html,"重置密码",successFn,yesFn,["400px","250px"])
    }
    
    //返回
    ns.goBack=function(){
    	ns.gridId="grid";
    	var ids = $.map( tree.getAllChildNodes(), function(h) { return h.org_id;}).join(',');
    	var filter =  searchs.getData();
    	if(ids){
			filter.push({opera: "in", field: "org_id", value: ids});
		}
        grid.reLoadConfig("grid",filter);
    }
    
    //应用授权
    ns.authorize=function(){
        var  node = tree.getSelectedNode();
        if(!node){
            $.toast(0,"请选择部门！");
            return;
        }
        ns.gridId="grid-authorize";
        grid.reLoadConfig("grid-authorize",[{ field: "{org_id}", value: node.org_id}]);
    }
    
    //授权保存
    ns.save=function (index){
    	var node = tree.getSelectedNode(); 
        var data = $("#grid").serializeJson();
        var obj={};
        for(var i in data){
        	if(data[i]){
        		obj[i] = data[i];
        	}
        }
        var param={
        	actions:$.isEmptyObject(obj) ?  "" : JSON.stringify(obj),
        	org_id:node.org_id
        }
        $.ajaxs("/admin/soft/system_user/action",param,function(res){
        	$.toast(1,"授权成功！");
        });
    }
    
    //初始化授权选中
    ns.initAuthorizeCheck=function(rows){
        if(ns.gridId == "grid-authorize"){
        	$.each(rows,function(index,o){
        		var actionObj = o.action != "''" && o.action ?  JSON.parse(o.action) : {};
        		var actions = String(actionObj[o.func_code]).split(',');
        		$.map(actions, function(h) {
        			$('#grid').find("input[name='"+o.func_code+"'][value='"+h+"']").prop("checked",true);
        		});
        	});
        	layui.form.render();
    	}
    }
    
    //清空所有
    ns.emptyCheckAll=function(func_code){
    	$('#grid').find("label>input[type='checkbox']").prop("checked",false);
    	layui.form.render();
    }
    
    //选中所有
    ns.checkAll=function(func_code,is){
        $('#grid').find("label>input[type='checkbox']").prop("checked",true);
        layui.form.render();
    }
    
    //选中所有查询
    ns.checkAllQuery=function(func_code,is){
    	$('#grid').find("input[value='00']").prop("checked",true);
    	layui.form.render();
    }
    
    //行全选和清空
    ns.rowCheck=function(func_code,is){
    	$('#grid').find("input[name='"+func_code+"']").prop("checked",is == "true" ? true : false);
    	layui.form.render();
    }
    
    //编辑权限
    ns.editAction=function(){
        var selectedRow=grid.getSelectedRows()[0];
        var filter={
            url:"system/pageMng/edit",
            oid:selectedRow.nav_id,
            mode:2
        }
        $.openWin(filter, "编辑父页面",['750px', '500px']); 
    }
    
    return ns;
}({}));

$(function(){ page.init();  })



jQuery.fn.extend({
	serializeJson: function() {
		var $th = this;
		var Input = $th.find("input");
		var Select = $th.find("select");
		var Textarea = $th.find("textarea");
		var Checkbox = $th.find("input[type='checkbox']");
		var Radio = $th.find("input[type='radio']");
		var Search = $th.find("div[type='search']");
		var obj = {};
		function treatmen(dom) {
			$.each(dom, function() {
				if(this.type == "button" || this.type == "checkbox" || this.type == "radio") {
				    return true;
				};
				if($(this).parents('.layui-table').length >0 ){
					return true;
				}
				if($(this).attr("form-datatype")=="number" && this.name){
				    obj[this.name] = Number($.delcommafy($.trim(this.value))); 
				}else if($(this).attr("type")=="number" && this.name){
				    obj[this.name] = Number($.trim(this.value)); 
				}else if(this.name){
				    obj[this.name] = $.trim(this.value); 
				}
			});
		};
		function twoTreatment(dom) {
			var names = $.unique( $.map(dom, function(h) {
			    if( $(h).attr("name")!="layTableCheckbox" ){
					return $(h).attr("name")
				}
			}) );
			$.each(names, function(index, o) {
				var box = $th.find("input[name='" + o + "']:checked");
				obj[o]=$.map(box, function(h) { return  $.trim(h.value)   }).join(',');
			});
		};
		function search(dom){
            $.each(dom, function() {
                if($(this).attr("name")){
                    obj[$(this).attr("name")] = $.trim($(this).attr("data-value")); 
                }
            });
        }
		treatmen(Input);
		treatmen(Textarea);
		treatmen(Select);
		twoTreatment(Checkbox);
		twoTreatment(Radio);
		search(Search);
		//转义script标签
		return $.scriptEncode(obj);
	}
});